package com.etc.controller;

import com.etc.domian.User;
import com.etc.domian.UserImage;
import com.etc.domian.WangEditor;
import com.etc.wrapper.FastDFSClientWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @Author kalista
 * @Description
 * @Date 2020/9/15  15:12
 **/
@Slf4j
@Controller
public class UploadController {


    @Autowired
    private FastDFSClientWrapper fastDFSClientWrapper;

    @Autowired
    private MongoTemplate mongoTemplate;


    //图片上传
    @PostMapping(value = "upload")
    @ResponseBody
    public WangEditor uploadFile(
            @RequestParam("myFile") MultipartFile multipartFile, HttpServletRequest request) throws IOException {
//            String fileName = multipartFile.getOriginalFilename();  // 文件名
//            String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
//======================= 普通上传 ==============
//            String filePath = "D://temp-rainy//"; // 上传后的路径
//            fileName = UUID.randomUUID() + suffixName; // 新文件名
//            File dest = new File(filePath + fileName);
//            if (!dest.getParentFile().exists()) {
//                dest.getParentFile().mkdirs();
//            }
//            try {
//                multipartFile.transferTo(dest);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//
//            String url = request.getScheme() + "://" + request.getServerName()
//                    + ":" + request.getServerPort() +  "/temp-rainy/" + fileName;
//===================== FastDFS上传=======================
        String s = fastDFSClientWrapper.uploadFile(multipartFile);
        HttpSession session = request.getSession();
        UserImage userImage = new UserImage();
        User user = (User) session.getAttribute("user");
        userImage.setId(UUID.randomUUID().toString().replaceAll("-",""));
        userImage.setImageUrl(s);
        userImage.setUserId(user.getId().toString());

        UserImage save = mongoTemplate.save(userImage);
        System.out.println(save.toString());
        String[] str = {s};
        WangEditor we = new WangEditor(str);
        return we;

    }

}
